package com.zzb.myshowme.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * Created by Administrator on 2016/11/1.
 * 将base64字符串转换为图片
 */
public class Base64ImageUtils {
    private Base64ImageUtils() {
        throw new AssertionError("no neeed create a instance");
    }

    private static byte[] getBitmapByte(String base64String) {
        if (base64String == null || base64String.length() == 0) {
            return null;
        }
        try {
            byte[] decode = Base64.decode(base64String, Base64.DEFAULT);
            return decode;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static Bitmap getBitmapFromBase64String(String base64String) {
        byte[] bitmapByte = getBitmapByte(base64String);
        if(bitmapByte == null) {
            return null;
        }
        return BitmapFactory.decodeByteArray(bitmapByte, 0, bitmapByte.length);
    }

    /**
     * 将图片转换为Base64字符串
     *
     * @return
     */
    public static String getBase64FromBitmap(Bitmap bitmap) {
        String bitmapStr = "";
        if (bitmap != null) {
            ByteArrayOutputStream bos = null;
            try {
                bos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bos);//将bitmap放入字节数组流中
//                bitmap.compress(Bitmap.CompressFormat.PNG, 90, bos);//将bitmap放入字节数组流中
                bos.flush();//将bos流缓存在内存中的数据全部输出，清空缓存
                bos.close();
                byte[] bitmapByte = bos.toByteArray();
                bitmapStr = Base64.encodeToString(bitmapByte, Base64.DEFAULT);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return bitmapStr;
    }
}
